<script lang="ts">
// 导入所需的组件和服务
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import { deletetask, taskService, acceptTask } from '@/api/task.js';
import { User, SwitchButton, Edit, Delete } from '@element-plus/icons-vue'
import { useTokenStore } from '@/stores/token';
import router from '@/router';
import AIChatBox from '@/components/AIChatBox.vue'
import PrivateChat from '@/components/PrivateChat.vue'

const pageNum = ref(1)
const pageSize = ref(20)
const total = ref(0)//总条数

//当每页条数发生了变化，调用此函数
const handleSizeChange = (size) => {
  pageSize.value = size
  getTasks()
}

//当前页码发生变化，调用此函数
const handleCurrentChange = (page) => {
  pageNum.value = page
  getTasks()
}

// 获取任务列表的异步函数
const getTasks = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  }
  let result = await taskService(params);
  tasks.value = result.data.items
  total.value = result.data.total
}
getTasks();

const handleCommand = (command) => {
  if (command === 'logout') {
    //退出登录
    ElMessageBox.confirm(
      '你确认退出登录吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(async () => {
        try {
          // 清空pinia中的token和个人信息
          const tokenStore = useTokenStore();
          tokenStore.removeToken();

          // 跳转到登录页
          router.push('/login');

          // 更新 localStorage
          localStorage.setItem('isLoggedIn', 'false');
        } catch (error) {
          console.error("发生误：", error);
          // 可以选择是否在这里显示错误消息或其他处理
        }
      })
      .catch(() => {
        // 用户点击了取消
        ElMessage({
          type: 'info',
          message: '取消退出',
        });
      });
  }
}


const deleterequirement = (row) => {
  ElMessageBox.confirm(
    '你确认删除该任务信息吗？',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      //用户点击了确认
      let result = await deletetask(row.id)
      ElMessage.success( result.data?result.data:'删除成功')
      getTasks()
    })
    .catch(() => {
      //用户点击了取消
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}


// 定义任务数据
const tasks = ref([
  {
    "id": '',
    "taskType": "",
    "title": "",
    "content": "",
    "budget": '',
    "authorId": 0,
    "contactPerson": "",
    "contactInfo": "",
    "createTime": "",
    "updateTime": ""
  }
]);

onMounted(() => {
  getTasks();
});


// 导出默认组件
export default {
  // 定义组件的数据
  data() {
    return {
      activeIndex: '',
      handleSelect: '',
      searchQuery: '',
      tasks,
      total,
      SwitchButton,
      User,
      Edit,
      Delete,
      userAvatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
      isDark: false,
      pageNum,
      pageSize,
      handleSizeChange,
      handleCurrentChange,
      handleCommand,
      query: '',
      showChat: false,
      currentTask: null,
      chatMode: 'select',
      showOrderConfirm: false,
      dialogVisible: false,
      currentTaskDetail: null,
      TASK_STATUS: {
        AVAILABLE: '可接单',
        IN_PROGRESS: '进行中',
        CANCELLED: '已取消',
        COMPLETED: '已完成'
      }
    };
  },

  // 注册组件
  components: {
    SwitchButton,
    User,
    AIChatBox,
    PrivateChat
  },

  // 计算属性
  computed: {
    // 过滤后的任务列表
    filteredItems() {
      const selectedTypes = this.taskTypes.filter(type => type.checked);
      if (selectedTypes.length === 0 || selectedTypes[0].id === 1) {
        // 如果选择了"全部"或者没有选择任何类型，返回所有内容
        return this.tasks; // 修改此处，从 this.items 改为 this.tasks
      }

      // 根据选中的类型过滤内容
      return this.tasks.filter(task => selectedTypes.some(type => task.taskType === type.name)); // 修改此处，按 task.taskType 和 type.name 进行比较
    },
    drawerTitle() {
      if (this.chatMode === 'ai') {
        return 'AI助手咨询'
      } else if (this.chatMode === 'private') {
        return `与 ${this.currentTask?.contactPerson || '发布者'} 沟通`
      } else {
        return '选择沟通方式'
      }
    },
  },
  // 组件的方法
  methods: {
    // 处理图片加载错误
    handleError(event) {
      event.target.onerror = null;
      event.target.src = 'images/default-logo.jpg';
    },

    // 搜索功能
    search() {
      console.log(this.query);
    },

    // 跳转到登录页面
    navigateTologin(page) {
      this.$router.push(`/${page}`); // 跳转到登录页面
    },

    // 跳转到注册页面
    navigateToregister(page) {
      this.$router.push(`/${page}`); // 跳转到登录页面
    },

    // 处理任务沟通
    communicate(taskId) {
      console.log(`沟通任务编号：${taskId}`);
    },

    // 跳转到指定链接
    navigateTo(link) {
      window.location.href = link;
    },

    // 选择任务类型
    selectType(type) {
      if (type.id === 1) {
        // 如果选择了"全部"，取消其他类型的选择
        this.taskTypes.forEach(t => t.checked = t.id === 1);
      } else {
        // 处理其他类型的选择状态
        const allChecked = this.taskTypes.every(t => !t.checked);
        type.checked = !type.checked; // 切换当前类型的选择状态

        // 如果当前类型被选择取消"全部"的选择
        if (type.checked) {
          this.taskTypes[0].checked = false;
        } else if (allChecked) {
          this.taskTypes[0].checked = true; // 如果所有都取消选择，选择"全部"
        }
      }
    },
    deleterequirement,
    handleChat(task) {
      const tokenStore = useTokenStore();
      if (!tokenStore.token) {
        ElMessage.warning('请先登录后再进行操作');
        router.push('/login');
        return;
      }

      this.currentTask = task;
      this.chatMode = 'select';
      this.showChat = true;
      // 重置接单确认状态
      this.showOrderConfirm = false;
    },

    // 添加切换联系方显示的方法
    toggleContact(row) {
      // 使用 Vue 的 $set 方法确保响应性
      this.$set(row, 'isContactVisible', !row.isContactVisible)
    },

    // 修改获取任务列表的方法
    async getTasks() {
      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }
      let result = await taskService(params);
      // 为每个任务添加联系方式显示状态
      this.tasks = result.data.items.map(task => ({
        ...task,
        isContactVisible: false
      }));
      this.total = result.data.total;
    },

    startPrivateChat() {
      const tokenStore = useTokenStore();
      if (!tokenStore.token) {
        ElMessage.warning('请先登录后再进行私聊');
        return;
      }
      this.chatMode = 'private';
    },

    async confirmOrder() {
      if (!this.currentTask) {
        ElMessage.warning('无法获取任务信息');
        return;
      }

      try {
        await ElMessageBox.confirm(
          '确认接受该任务吗？接单后将建立合作关系。',
          '接单确认',
          {
            confirmButtonText: '确认接单',
            cancelButtonText: '取消',
            type: 'info'
          }
        );

        // 调用接单 API
        const response = await acceptTask(this.currentTask.id);
        
        ElMessage.success('接单成功！');
        this.showChat = false;
        
        // 刷新任务列表
        await this.getTasks();
        
      } catch (error) {
        if (error === 'cancel') {
          ElMessage.info('已取消接单');
        } else {
          // 显示具体的错误信息
          const errorMsg = error.response?.data?.message || error.message || '接单失败，请稍后重试';
          console.error('接单失败:', error);
          ElMessage.error(errorMsg);
        }
      }
    },

    // 添加 AI 助手聊天方法
    startAIChat() {
      const tokenStore = useTokenStore();
      if (!tokenStore.token) {
        ElMessage.warning('请先登录后再使用 AI 助手');
        return;
      }
      this.chatMode = 'ai';
      ElMessage.success('AI 助手已准备就绪，开始咨询吧！');
    },

    // 添加查看详情方法
    showTaskDetail(task) {
      this.currentTaskDetail = task;
      this.dialogVisible = true;
    },

    // 添加 AI 助手按钮的处理方法
    async handleAIButton(type) {
        const tokenStore = useTokenStore();
        if (!tokenStore.token) {
            ElMessage.warning('请先登录后再使用 AI 助手');
            return;
        }

        if (!this.currentTask) {
            ElMessage.warning('无法获取任务信息');
            return;
        }

        // 直接发送对应类型的消息给 AI 助手
        if (this.$refs.aiChatBox) {
            await this.$refs.aiChatBox.sendMessage(type);
        }
    },

    // 判断是否是任务作者
    isTaskAuthor(task) {
        const tokenStore = useTokenStore();
        return task.authorId === tokenStore.token.valueOf;
    },

    // 编辑任务
    editTask(task) {
        // TODO: 实现编辑任务的逻辑
        console.log('编辑任务:', task);
    },

    // 查看任务进度
    viewTaskProgress(task) {
        // TODO: 实现查看任务进度的逻辑
        console.log('查看任务进度:', task);
    },

    // 查看任务详情
    viewTaskDetail(task) {
        // TODO: 实现查看任务详情的逻辑
        console.log('查看任务详情:', task);
    },

    getStatusType(status) {
        console.log('Current status:', status);
        
        const types = {
            '可接单': 'success',
            '进行中': 'warning',
            '已完成': 'info',
            '已取消': 'danger'
        }
        return types[status] || 'success';
    }
  }
}
</script>

<template>
  <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" :ellipsis="false" @select="handleSelect"
    style="height:75px;box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
    <el-menu-item index="0">
      <img style="width: 100px;height: 70px;margin-left: 53px;margin-right: 10px;" src="@/assets/logo.jpg"
        alt="CodeCash" />
    </el-menu-item>
    <el-search-item index="1" style="transform: translate(-90%,15px);">
      <el-input v-model="searchQuery" style="width: 320px;height:40px;" placeholder="搜索您感兴趣的内容" clearable />
      <el-button type="search" style="height: 40px;background-color:#007bff;color:white;">搜索</el-button>
    </el-search-item>
    <el-router-menu index="2" style="transform: translateX(-2%);">
      <el-link href="/" style="color: black; font-size: 18px;padding: 20px;">首页</el-link>
      <el-link href="/programmer" style="color: black; font-size: 18px;padding: 20px;">程序员</el-link>
      <el-link href="/task" style="color: black; font-size: 18px;padding: 20px;">任务大厅</el-link>
      <el-link href="/community" style="color: black; font-size: 18px;padding: 20px;">社区</el-link>
      <el-link href="/user/call" style="color: black; font-size: 18px;padding: 20px;">联系我们</el-link>
    </el-router-menu>
    <el-buttons-item index="3" style="transform: translateY(25%);margin-right: 20px;">
      <el-dropdown placement="bottom-end">
        <el-avatar :src="userAvatar" size="medium" />
        <el-icon>
          <CaretBottom />
        </el-icon>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="userInfo" :icon="User" @click="navigateTo('/userInfo')">个人中心</el-dropdown-item>
            <el-dropdown-item command="logout" :icon="SwitchButton"
              @click="handleCommand('logout')">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </el-buttons-item>
  </el-menu>
  <el-main>
    <el-table :data="tasks" style="width: 100%">
      <el-table-column label="序号" width="100" type="index">
        <template v-slot="slotProps">
          {{ (pageNum - 1) * pageSize + slotProps.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="任务类型" prop="taskType"></el-table-column>
      <el-table-column label="任务标题">
        <template #default="{ row }">
          {{ row.title }}
        </template>
      </el-table-column>
      <el-table-column label="任务详情" prop="content">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            link 
            @click="showTaskDetail(row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="预算" prop="budget"></el-table-column>
      <el-table-column label="联系人" prop="contactPerson"></el-table-column>
      <el-table-column label="联系方式">
        <template #default="{ row }">
          <span>********</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag 
            :type="getStatusType(row.status)"
            size="small"
          >
            {{ row.status || TASK_STATUS.AVAILABLE }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button 
              type="primary" 
              link
              @click="handleChat(row)"
            >
              立即沟通
            </el-button>
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-pagination style="margin-left: 580px;margin-top: 40px;color: #2994F2;" v-model:current-page="pageNum"
      v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]" :total="total"
      layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </el-main>
  <el-footer>
    <div class="footer">
      <a href="#">动态公告</a> |
      <a href="#">帮助</a> |
      <a href="#">关于我们</a> |
      <a href="#">合作伙伴</a> |
      <a href="#">意见反馈</a> |
      <text style="color: rgb(78, 77, 77);">@"码上有钱"程序员接单平台</text>
      <div class="credits">
        粤ICP备20220901号-4 | 粤公网安备33011002011599号
      </div>
    </div>
  </el-footer>

  <!-- 添加聊天抽屉 -->
  <el-drawer
    v-model="showChat"
    :title="drawerTitle"
    size="400px"
    direction="rtl"
    :destroy-on-close="false"
    :modal="true"
  >
    <div class="chat-wrapper">
      <div v-if="chatMode === 'select'" class="chat-actions">
        <el-button 
          type="primary" 
          @click="startPrivateChat"
          style="width: calc(100% - 40px); margin: 10px 20px;"
        >
          开始私聊
        </el-button>
        <el-button 
          @click="startAIChat"
          style="width: calc(100% - 40px); margin: 10px 20px;"
        >
          AI助手咨询
        </el-button>
      </div>

      <PrivateChat
        v-if="chatMode === 'private'"
        :target-id="currentTask?.authorId"
        :target-name="currentTask?.contactPerson"
        :target-avatar="currentTask?.avatar"
        @confirm-cooperation="showOrderConfirm = true"
      />

      
      <div v-if="chatMode === 'ai'" class="chat-wrapper">
        <div class="ai-buttons">
          <el-button 
            type="primary"
            @click="handleAIButton('analyze')"
            style="width: calc(100% - 40px); margin: 10px 20px;"
          >
            分析任务详情
          </el-button>
          <el-button 
            type="success"
            @click="handleAIButton('suggest')"
            style="width: calc(100% - 40px); margin: 10px 20px;"
          >
            获取任务建议
          </el-button>
          <el-button 
            type="warning"
            @click="handleAIButton('estimate')"
            style="width: calc(100% - 40px); margin: 10px 20px;"
          >
            评估任务情况
          </el-button>
        </div>

        <AIChatBox 
          ref="aiChatBox"
          :task-info="currentTask" 
        />
      </div>

      <div v-if="showOrderConfirm" class="order-confirm">
        <el-button 
          type="primary"
          @click="confirmOrder"
          style="width: calc(100% - 40px); margin: 10px 20px;"
        >
          确认接单
        </el-button>
      </div>
    </div>
  </el-drawer>

  <!-- 添加任务详情对话框 -->
  <el-dialog
    v-model="dialogVisible"
    title="任务详情"
    width="50%"
  >
    <template v-if="currentTaskDetail">
      <div class="task-detail-content">
        <div class="detail-item">
          <label>任务类型：</label>
          <span>{{ currentTaskDetail.taskType }}</span>
        </div>
        <div class="detail-item">
          <label>任务标题：</label>
          <span>{{ currentTaskDetail.title }}</span>
        </div>
        <div class="detail-item">
          <label>任务详情：</label>
          <p>{{ currentTaskDetail.content }}</p>
        </div>
        <div class="detail-item">
          <label>预算：</label>
          <span>{{ currentTaskDetail.budget }}</span>
        </div>
        <div class="detail-item">
          <label>联系人：</label>
          <span>{{ currentTaskDetail.contactPerson }}</span>
        </div>
      </div>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleChat(currentTaskDetail)">
          立即沟通
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 样式定义 */
.el-menu--horizontal>.el-menu-item:nth-child(1) {
  margin-right: auto;
}

.tasks-header {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.tasks-header label {
  margin-right: 15px;
  display: flex;
  align-items: center;
}

.tasks-header input[type="checkbox"] {
  margin-right: 5px;
}

.task-list {
  max-width: 1200px;
  margin: 10px auto;
}

.task {
  background-color: white;
  padding: 22px;
  margin-bottom: 10px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.task-info {
  position: relative;
  justify-content: flex-end;
  width: 100%;
}

.task-inline {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.bid-available {
  color: #2994F2;
  float: right;
  margin-right: -52px;
  margin-top: -31px;
  font-size: 20px;
}

.task-header {
  font-weight: bold;
  font-size: 20px;
}

.task-header::after {
  content: '';
  display: block;
  width: 1050px;
  height: 1px;
  background-color: #ccc;
  margin-top: 5px;
}

.task-details {
  margin: 10px 0;
  font-size: 20px;
}

.task-status {
  display: inline-block;
  background-color: #fff;
  padding: 2px 5px;
  margin-left: 15px;
  font-size: 14px;
  border-radius: 5px;
  border: solid 1px #007bff;
}

.task-points {
  color: red;
  margin-left: 15px;
  margin-right: 10px;
  font-size: 14px;
}

.task-action {
  font-size: 18px;
  background-color: #2994F2;
  color: white;
  border-radius: 5px;
  width: 50px;
  height: 30px;
  display: flex;
  margin-top: 80px;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  text-decoration: none;
}

.footer {
  margin-top: 100px;
  padding: 10px 0;
  border-top: 1px solid #ddd;
  text-align: center;
}

.footer a {
  text-decoration: none;
  color: rgb(78, 77, 77);
  background: transparent;
  border: none;
  cursor: pointer;
}

.footer .credits {
  margin-top: 5px;
  font-size: 12px;
  color: gray;
}

.el-button--link {
  padding: 0;
  height: auto;
  font-size: 14px;
}

.chat-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-actions {
  display: flex;
  flex-direction: column;
  padding: 20px 0;
}

.order-confirm {
  border-top: 1px solid #DCDFE6;
  padding: 10px 0;
  margin-top: auto;
}

.task-detail-content {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.detail-item p {
  margin: 10px 0;
  line-height: 1.6;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.operation-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
}

.operation-buttons .el-button {
    padding: 4px 8px;
    margin: 0;
}

.el-tag {
    margin-right: 8px;
}
</style>